<template>
  <div class="book-detail-view">
    <div class="book-detail-view-top">
      <div class="book-detail-img">
        <img class="book-detail-cover" :src="novel.coverImage" alt="封面" />
      </div>
      <div class="book-detail-info">
        <div class="book-detail-title">{{ novel.title }}</div>
        <div class="book-detail-kind">{{ novel.kindName }}</div>
        <div class="book-detail-author">{{ novel.author }}</div>
        <div class="book-detail-isEnd" v-if="novel.isEnd">已完结</div>
        <div class="book-detail-isEnd" v-else>连载中</div>
        <div class="mb-4">
          <el-button
            class="read-book"
            type="primary"
            round
            @click="readingBook(novel.id, novel.chapterList[0].id)"
            >开始阅读</el-button
          >
          <el-button
            v-if="!novel.isInBookShelf"
            class="add-book"
            color="#f6f6f6"
            round
            @click="addBookShelf"
            >加入书架</el-button
          >
          <el-button
            v-else
            class="add-book"
            color="#f6f6f6"
            round
            @click="removeBookShelf"
            >已加书架</el-button
          >
        </div>
      </div>
    </div>
    <div class="book-detail-content">
      <div class="book-detail-content-description">
        <div class="book-detail-content-description-title">作品简介</div>
        <el-divider />
        <el-text class="book-detail-content-description-text">{{
          novel.description
        }}</el-text>
      </div>
      <div class="book-detail-content-chapter">
        <div class="book-detail-content-chapter-title">
          目录 | {{ novel.totalChapter }}
        </div>
        <el-divider />
        <el-scrollbar height="300px">
          <p
            v-for="item in novel.chapterList"
            :key="item.chapterId"
            class="book-detail-content-chapter-text"
          >
            <router-link :to="'/novelReading/' + novel.id + '/' + item.id">
              第{{ item.chapterNum }}章 {{ item.chapterName }}</router-link
            >
          </p>
        </el-scrollbar>
      </div>
    </div>
    <div class="comments">
      <el-card style="max-width: 100%">
        <template #header>
          <div class="comments-header">
            <h3>留言区</h3>
          </div>
        </template>
        <div class="edit-box">
          <div class="edit-box-left">
            <el-avatar v-if="isLogin" :size="45" :src="avatar" />
            <el-avatar
              v-else
              :size="45"
              src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
            />
          </div>
          <div class="edit-box-middle">
            <el-input
              placeholder="与其赞同别人的话语，不如自己畅所欲言..."
              v-model="comment"
            ></el-input>
          </div>
          <div class="edit-box-right">
            <el-button @click="handlePublish(comment, null, null)"
              >发布</el-button
            >
          </div>
        </div>
        <!-- <el-scrollbar height="300px"> -->
        <div v-infinite-scroll="loadFatherComment">
          <div
            class="comment-area"
            v-for="(item, index) in comments"
            :key="index"
          >
            <div class="comment-father">
              <div class="comment-father-user">
                <el-avatar
                  @click="toUserCenter(item.fromUserId)"
                  :src="item.avatar"
                />
                <div class="comment-father-user-info">
                  <el-text class="comment-father-user-name">{{
                    item.username
                  }}</el-text>
                  <el-text class="comment-father-time">{{
                    item.createTime
                  }}</el-text>
                </div>
              </div>
              <div class="comment-father-content">
                <el-text>{{ item.content }}</el-text>
              </div>
              <div class="comment-father-reply">
                <img
                  v-if="!item.isGood"
                  class="good-pre"
                  @click="good(item)"
                  src="../assets/点赞.png"
                />
                <img
                  v-else
                  @click="cancelGood(item)"
                  class="good-pre"
                  src="../assets/点赞 (1).png"
                />
                <el-icon><ChatDotRound /></el-icon>
                <div @click="commentReply(item.fromUserId, item.id)">回复</div>
              </div>
            </div>
            <div
              class="comment-childs"
              v-for="childItem in item.childComments"
              :key="childItem.id"
            >
              <div class="comment-child">
                <div class="comment-child-user">
                  <el-avatar :src="childItem.avatar" />
                  <div class="comment-child-user-name">
                    <div class="comment-child-user-name-text">
                      <el-text v-if="childItem.toUserName">{{
                        childItem.name
                      }}</el-text>
                      <el-text v-else
                        >{{ childItem.username }} 回复
                        {{ childItem.toUsername }}
                      </el-text>
                    </div>
                    <div class="comment-child-user-time">
                      <el-text class="comment-child-time">{{
                        childItem.createTime
                      }}</el-text>
                    </div>
                  </div>
                </div>
                <div class="comment-child-content">
                  <el-text>{{ childItem.content }}</el-text>
                </div>
                <div class="comment-child-reply">
                  <img
                    v-if="!childItem.isGood"
                    class="good-pre"
                    @click="good(childItem)"
                    src="../assets/点赞.png"
                  />
                  <img @click="cancelGood(childItem)" v-else class="good-pre" src="../assets/点赞 (1).png" />
                  <el-icon><ChatDotRound /></el-icon>
                  <div @click="commentReply(childItem.fromUserId, item.id)">
                    回复
                  </div>
                </div>
              </div>
            </div>
            <div
              v-if="item.hasMore"
              @click="loadChildComment(item)"
              class="comment-child-more-icon"
            >
              <el-icon><CaretBottom /></el-icon>
            </div>
            <!-- <div :v-if="!hasMore" class="comment-father-more" v-if="item.hasMore">没有更多了</div> -->
          </div>
        </div>

        <!-- </el-scrollbar> -->
        <!-- <template #footer>Footer content</template> -->
      </el-card>
    </div>
    <div v-show="isReplying" class="comment-reply-input">
      <div class="edit-box-middle">
        <el-input
          ref="commentInputRef"
          autofocus="true"
          placeholder=""
          v-model="replyComment"
        ></el-input>
      </div>
      <div class="edit-box-right">
        <el-button @click="handlePublish(replyComment, toUserId, commentId)"
          >发布</el-button
        >
      </div>
      <div class="edit-box-right">
        <el-button @click="cancelReply()">取消</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, reactive } from "vue";
import {
  getMainComments,
  getChildComments,
  publishComment,
  addToBookShelf,
  removeFromBookShelf,
  addGood,
  cancelGood,
} from "@/api/novelReading"; // 假设你的API调用在这里
import { ElMessage, ElMessageBox } from "element-plus"; // 假设你使用Element Plus作为UI库
import { getUserInfo } from "@/api/userCenter";
import { getInfo } from "@/utils/storage";

export default {
  name: "BookDetailComponent",
  props: {
    novel: {
      type: Object,
      required: true,
    },
    id: String,
  },
  setup(props) {
    const comments = reactive([]);
    const page = ref(0);
    const size = ref(5);
    const hasMore = ref(true);
    const commentInputRef = ref(null);

    // 加载父级评论
    const loadFatherComment = async () => {
      console.log("加载父级评论");
      if (hasMore.value) {
        page.value += 1;
        const res = await getMainComments(props.id, page.value, size.value);
        if (res.data.success) {
          const result = res.data.result;
          const updatedComments = result.list.map(async (mainCommentItem) => {
            mainCommentItem.page = 0;
            mainCommentItem.size = size.value;
            Reflect.set(mainCommentItem, "childComments", []);
            await loadChildComment(mainCommentItem);
            return mainCommentItem;
          });

          // 由于 map 返回的是一个 Promise 数组，我们需要等待所有 Promise 完成
          const allComments = await Promise.all(updatedComments);
          comments.push(...allComments);
          hasMore.value = result.hasMore;
        }
      }
    };

    // 加载子级评论
    const loadChildComment = async (parentComment) => {
      console.log("加载子级评论");
      parentComment.page += 1;
      const res = await getChildComments(
        parentComment.id,
        parentComment.page,
        parentComment.size
      );
      if (res.data.success) {
        parentComment.childComments = [
          ...parentComment.childComments,
          ...res.data.result.list,
        ];
        parentComment.hasMore = res.data.result.hasMore;
      }
    };

    // 在组件创建时加载父级评论
    onMounted(() => {
      loadFatherComment();
    });

    // 返回给模板的响应式数据和函数
    return {
      comments,
      commentInputRef,
      loadFatherComment,
      loadChildComment,
    };
  },
  data() {
    return {
      isReplying: false,
      replyComment: "",
      comment: "",
      toUserId: "",
      commentId: "",
      userId: "",
      avatar: "",
      //isLogin: false,
    };
  },
  methods: {
    // 回复评论（注意：这里的index需要从模板中传递）
    commentReply(toUserId, commentId) {
      this.toUserId = toUserId;
      this.commentId = commentId;
      this.isReplying = true;
    },
    // 点赞
    async good(item) {
      if(this.isLogin) {
        const res = await addGood(item.id);
        if (res.data.success) {
          item.isGood = true;
        }
      } else {
        this.$router.push({
          name: "login"
        });
      }
    },
    // 取消点赞
    async cancelGood(item) {
      if(this.isLogin) {
        const res = await cancelGood(item.id);
        if (res.data.success) {
          item.isGood = false;
        }
      } else {
        this.$router.push({
          name: "login"
        });
      }
    },
    // 跳转到个人中心
    toUserCenter(id) {
      this.$router.push("/home/userCenter/" + id + "/myComments");
    },

    // 添加到书架
    async addBookShelf() {
      if (this.isLogin) {
        // 假设token存储在localStorage中
        const res = await addToBookShelf(
          //localStorage.getItem("userId"),
          getInfo().userId,
          this.id,
          this.novel.chapterList[0].id
        );
        if (res.data.success) {
          ElMessage({
            type: "success",
            message: "加入书架成功",
          });
          location.reload();
        }
      } else {
        ElMessage({
          type: "warning",
          message: "尚未登录",
        });
      }
    },

    // 从书架移除
    async removeBookShelf() {
      if (this.isLogin) {
        ElMessageBox.confirm("确认要从书架中移除该小说?", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            const res = await removeFromBookShelf(
              localStorage.getItem("userId"),
              this.novel.id
            );
            if (res.data.success) {
              ElMessage({
                type: "success",
                message: "已从书架移除",
              });
              location.reload();
            }
          })
          .catch(() => {});
      } else {
        ElMessage({
          type: "warning",
          message: "尚未登录",
        });
      }
    },

    cancelReply() {
      this.toUserId = "";
      this.commentId = "";
      this.isReplying = false;
    },
    // 阅读小说
    readingBook(novelId, chapterId) {
      this.$router.push({
        name: "novelReading",
        params: { novelId, chapterId },
      });
    },

    // 发布评论
    async handlePublish(comment, toUserId, commentId) {
      if (comment.trim() === "") {
        ElMessage({
          showClose: true,
          type: "warning",
          message: "评论不能为空",
        });
      } else {
        ElMessageBox.confirm("确认发布吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            const res = await publishComment(
              this.$route.params.id,
              comment,
              toUserId,
              commentId
            );
            if (res.data.success) {
              ElMessage({
                type: "success",
                message: "发布成功",
              });
              location.reload();
            } else {
              ElMessage({
                type: "error",
                message: res.data.message,
              });
            }
          })
          .catch(() => {});
      }
    },

    // 加载用户信息
    async loadUserInfo() {
      if (!this.isLogin) {
        return;
      }
      const res = await getUserInfo(this.$store.state.user.userInfo.userId);
      if (res.data.success) {
        this.userId = res.data.result.id;
        this.avatar = res.data.result.avatar;
      } else {
        ElMessage({
          type: "error",
          message: res.data.message,
        });
      }
    },
  },
  computed: {
    isLogin() {
      if (this.$store.state.user.userInfo.token) {
        return true;
      } else {
        return false;
      }
    },
  },
  created() {
    this.loadUserInfo();
  },
};
</script>

<style>
.book-detail-view {
  background-color: #f6f6f6;
  width: 100%;
  display: grid;
  justify-content: center;
}
.book-detail-view-top {
  display: flex;
  justify-content: center;
  width: 1240px;
  margin: 0 auto;
  padding: 30px 20px 45px;
  height: 300px;
  background-color: #ffffff;
}
.book-detail-cover {
  max-width: 150px;
  max-height: 200px;
  border-radius: 10px;
  margin-right: 20px;
}
.book-detail-img {
  position: relative;
  top: 40px;
  left: -350px;
}
.book-detail-info {
  position: relative;
  top: 40px;
  left: -340px;
  flex-direction: column;
  justify-content: center;
}
.book-detail-title {
  font-size: 30px;
  font-weight: bold;
}
.book-detail-kind {
  margin: 5px 0;
}
.book-detail-author {
  margin: 5px 0;
}
.mb-4 {
  margin: 50px 0;
}
.read-book {
  background-image: linear-gradient(117deg, #ff9000 12%, #ff4f00 87%);
}
.add-book {
  background-color: #f6f6f6;
}
.book-detail-isEnd {
  position: relative;
  top: 30px;
  font-size: large;
}
.book-detail-content {
  width: 1000px;
  background-color: #ffffff;
  margin: 10% 0;
  display: grid;
  margin: 50px auto;
}
.book-detail-content-description {
  margin: 0 20px;
}
.book-detail-content-description-title {
  font-size: large;
  margin: 20px 10px;
}
.book-detail-content-chapter {
  margin: 0 20px;
}
.book-detail-content-chapter-title {
  font-size: large;
  margin: 20px 10px;
}
.book-detail-content-chapter-text {
  margin: 0 0 0 0;
}
.comments {
}
.comments-header {
  display: flex;
  align-items: center;
  height: 30px;
}
.edit-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.edit-box-left {
}
.edit-box-middle {
  width: 85%;
}
.comment-area {
  margin: 10px 20px;
  display: grid;
}
.comment-father {
  margin: 10px 20px;
}
.comment-father-user-info {
  display: flex;
  margin: 0 10px;
  justify-content: space-between;
  width: 1100px;
  align-items: center;
}
.comment-father-content {
  margin: 0px 0px 0px 60px;
}
.comment-father-user {
  display: flex;
  margin: auto 10px;
}
.comment-childs {
  margin: 0 0 0 80px;
  display: grid;
  background-color: rgb(228, 228, 228);
}
.comment-child {
  display: grid;
  margin: 5px 20px;
}
.comment-child-user {
  display: flex;
}
.comment-child-user-name {
  display: flex;
  margin: 0 10px;
  justify-content: space-between;
  width: 1030px;
  align-items: center;
}
.comment-child-content {
  margin: 0px 0px 0px 50px;
}
.comment-child-more-icon {
  height: 26px;
  margin: 0px 0px 0px 80px;
  background-color: rgb(228, 228, 228);
  display: flex;
  justify-content: center;
}
.comment-father-reply {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  font-size: small;
  margin-right: 20px;
}
.comment-child-reply {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  font-size: small;
  margin-right: 20px;
}
.comment-reply-input {
  position: fixed;
  left: 100px;
  right: 100px;
  top: 90%;

  width: 1300px;
  height: 20px;
  display: flex;
  justify-content: center;
}
.good-pre {
  width: 20px;
  height: 20px;
  margin: 10px 5px;
}
</style>